﻿using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace libVNEditor
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            RefreshForm();
        }

        CPlot plot = new CPlot() { name = "新剧情" };

        public CPlot Plot { get => plot; set => plot = value; }

        public void RefreshForm()
        {
            treeView_plot.Nodes.Clear();
            treeView_plot.Nodes.Add(plot.name);
            foreach (CLabel label in plot.labels)
            {
                TreeNode node_label = new TreeNode { Text = label.LabelName , ImageIndex = Const.Level.LABEL};
                foreach (CSentence sentence in label.sentences)
                {
                    TreeNode node_sentence = new TreeNode { Text = string.Format("{0}:{1}", sentence.Speaker, sentence.plainText), ImageIndex = Const.Level.SENTENCE };
                    foreach (CEvent ev in sentence.events)
                    {
                        TreeNode node_event = new TreeNode { Text = string.Format("[{0}]{1}", ev.type, ev.name), ImageIndex = Const.Level.EVENT };
                        foreach (CAction action in ev.actions)
                        {
                            TreeNode node_action = new TreeNode { Text = action.command };
                            foreach(Argument arg in action.args)
                            {
                                TreeNode node_arg = new TreeNode { Text = string.Format("{0} = {1}", arg.name, arg.value) };
                                node_action.Nodes.Add(node_arg);
                            }
                            node_event.Nodes.Add(node_action);
                        }
                        node_sentence.Nodes.Add(node_event);
                    }
                    node_label.Nodes.Add(node_sentence);
                }
                treeView_plot.Nodes[0].Nodes.Add(node_label);
            }
            treeView_plot.ExpandAll();
        }

        private void CreateLabelClick(object sender, EventArgs e)
        {
            string name = Interaction.InputBox("请输入标签名:");
            if(name == "")
            {
                MessageBox.Show("标签名不能为空!");
                return;
            }
            CLabel label = new CLabel
            {
                LabelName = name
            };
            plot.labels.Add(label);
            RefreshForm();
        }

        private void RefreshClick(object sender, EventArgs e)
        {
            RefreshForm();
        }

        private void OnEdit(object sender, EventArgs e)
        {
            TreeNode select = treeView_plot.SelectedNode;
            if (select == null) return;
            switch(select.Level)
            {
                case Const.Level.PLOT:
                    plot.ShowDialog();
                    RefreshForm();
                    break;
                case Const.Level.LABEL:
                    plot.labels[select.Index].ShowDialog();
                    RefreshForm();
                    break;
                case Const.Level.SENTENCE:
                    plot.labels[select.Parent.Index].sentences[select.Index].ShowDialog();
                    RefreshForm();
                    break;
                case Const.Level.EVENT:
                    plot.labels[select.Parent.Parent.Index].sentences[select.Parent.Index].events[select.Index].ShowDialog();
                    RefreshForm();
                    break;
                case Const.Level.ACTION:
                    plot.labels[select.Parent.Parent.Parent.Index].sentences[select.Parent.Parent.Index].events[select.Parent.Index].actions[select.Index].ShowDialog();
                    RefreshForm();
                    break;
            }
        }

        //保存文件
        private void SaveFileClick(object sender, EventArgs e)
        {
            string path;
            //Console.WriteLine(plot.ToString());
            if(Common.filePath == "")
            {
                DialogResult result = saveFileDialog.ShowDialog();
                if (result != DialogResult.OK) return;
                path = saveFileDialog.FileName;
                Text = "libVN剧情设计辅助系统 - " + path;
            }
            else
            {
                path = Common.filePath;
            }
            File.WriteAllText(path, plot.ToString());
            Common.filePath = path;
        }

        //文件另存为
        private void SaveAsClick(object sender, EventArgs e)
        {
            string path;
            DialogResult result = saveFileDialog.ShowDialog();
            if (result != DialogResult.OK) return;
            path = saveFileDialog.FileName;
            File.WriteAllText(path, plot.ToString());
            Common.filePath = path;
            Text = "libVN剧情设计辅助系统 - " + path;
        }

        private void OpenFileClick(object sender, EventArgs e)
        {
            try
            {
                string path;
                DialogResult result = openFileDialog.ShowDialog();
                if (result != DialogResult.OK) return;
                path = openFileDialog.FileName;
                string file = File.ReadAllText(path);
                //todo:完成读取文件的功能

                XmlDocument xml = new XmlDocument();
                xml.LoadXml(file);
                CPlot plot_read = new CPlot();

                XmlNode root = xml.SelectSingleNode("plot");
                plot_read.name = ((XmlElement)root).GetAttribute("name");
                plot_read.width = int.Parse(((XmlElement)root).GetAttribute("width"));
                plot_read.height = int.Parse(((XmlElement)root).GetAttribute("height"));

                XmlNodeList labels = root.ChildNodes;
                foreach (XmlNode label in labels)
                {
                    XmlElement xe_label = (XmlElement)label;
                    string label_name = xe_label.GetAttribute("name");
                    CLabel l = new CLabel() { LabelName = label_name };

                    XmlNodeList sentences = label.ChildNodes;
                    foreach (XmlNode sentence in sentences)
                    {
                        XmlElement xe_sentence = (XmlElement)sentence;
                        string speaker = xe_sentence.GetAttribute("speaker");
                        XmlNode node_rtf = sentence.SelectSingleNode("richtext");
                        string rtf = ((XmlElement)node_rtf).InnerText;
                        CSentence s = new CSentence { Speaker = speaker, richText = rtf };

                        XmlNodeList events = sentence.SelectSingleNode("events").ChildNodes;
                        foreach (XmlNode ev in events)
                        {
                            XmlElement xe_event = (XmlElement)ev;
                            string _type = xe_event.GetAttribute("type");
                            string _name = xe_event.GetAttribute("name");
                            CEvent v = new CEvent { type = _type, name = _name };

                            XmlNodeList actions = ev.ChildNodes;
                            foreach (XmlNode action in actions)
                            {
                                XmlElement xe_action = (XmlElement)action;
                                string cmd = xe_action.GetAttribute("command");
                                string cond = xe_action.GetAttribute("condition");
                                CAction act = new CAction { command = cmd, condition = cond };

                                XmlNodeList args = action.ChildNodes;
                                foreach (XmlNode arg in args)
                                {
                                    XmlElement xe_arg = (XmlElement)arg;
                                    string argname = xe_arg.GetAttribute("name");
                                    string _val = xe_arg.GetAttribute("value");
                                    Argument argu = new Argument { name = argname, value = _val };
                                    act.args.Add(argu);
                                }
                                v.actions.Add(act);
                            }
                            s.events.Add(v);
                        }
                        l.sentences.Add(s);
                    }
                    plot_read.labels.Add(l);
                }
                plot = plot_read;

                XmlNode node_characters = xml.SelectSingleNode("characters");
                XmlNodeList cs = node_characters.ChildNodes;
                foreach(XmlNode node_c in node_characters)
                {
                    XmlElement xe_c = (XmlElement)node_c;
                    string _name = xe_c.GetAttribute("name");
                    Character c = new Character { name = _name };
                    plot_read.characters.Add(c);
                }

                Common.filePath = path;
                Text = "libVN剧情设计辅助系统 - " + path;
                RefreshForm();
            }
            catch
            {
                MessageBox.Show("打开文件时出现错误！\n");
            }
            
        }

        private void CreateNewFileClick(object sender, EventArgs e)
        {
            if(MessageBox.Show("确定要用空白文件覆盖当前文件吗？","新建文件", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                plot = new CPlot();
                RefreshForm();
            }
        }

        private void CloseCurrentFileClick(object sender, EventArgs e)
        {
            if(MessageBox.Show("我也不知道你保存了吗。\n确定要关闭吗？", "关闭文件", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                Application.Exit();
            }
        }

        private void ToolItem_CharacterManager_Click(object sender, EventArgs e)
        {
            CharacterManagerForm cmf = new CharacterManagerForm();
            cmf.Show();
        }
    }
}
